import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import LoginForm from '../../components/LoginForm';
import styles from './styles.module.css';

const getBaseUrl = () => {
  const protocol = window.location.protocol === 'https:' ? 'https:' : 'http:';
  const baseURL = protocol + '//api.woniutech.com';
  return baseURL;
};

const Login: React.FC = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (data: {
    adminName: string;
    password: string;
    rememberMe: boolean;
  }) => {
    setIsLoading(true);
    setErrorMsg('');
    try {
      const baseURL = getBaseUrl();
      const response = await fetch(`${baseURL}/api/admin/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          adminName: data.adminName,
          password: data.password,
        }),
      });
      const result = await response.json();
      if (result.success === true) {
        if (result.data) {
          localStorage.setItem('Authorization', result.data);
        }
        navigate('/prompt-template-manager');
      } else {
        setErrorMsg(result?.message || result?.errorMsg || '登录失败，请检查用户名和密码');
      }
    } catch (error) {
      setErrorMsg('网络异常，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <h1 className={styles.title}>欢迎登录</h1>
        {errorMsg && <div style={{ color: 'red', marginBottom: 16 }}>{errorMsg}</div>}
        <LoginForm onSubmit={handleSubmit} isLoading={isLoading} />
      </div>
    </div>
  );
};

export default Login; 